package com.hkts.naturalgas.flow.service.serviceimpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hkts.naturalgas.feign.FeignInterface;
import com.hkts.naturalgas.flow.entity.FlowInstanceinfo;
import com.hkts.naturalgas.flow.entity.FlowTemplateinfo;
import com.hkts.naturalgas.flow.mapper.FlowInstanceinfoMapper;
import com.hkts.naturalgas.flow.mapper.FlowTemplateinfoMapper;
import com.hkts.naturalgas.flow.service.IFlowInstanceinfoService;
import com.hkts.naturalgas.flow.service.IFlowTaskInstanceService;
import com.hkts.naturalgas.flow.service.IFlowTemplateinfoCopyService;
import com.hkts.naturalgas.flow.service.IFlowUserinfoService;
import com.hkts.naturalgas.organizational.mapper.HontUserMapper;
import com.hkts.naturalgas.organizational.orgVo.HontUserRolelevelQueryVo;
import com.hkts.naturalgas.organizational.orgVo.HontUserRolelevelVo;
import com.hkts.naturalgas.organizational.service.IHontUserService;
import com.hkts.naturalgas.performance.performanceTo.HontUserTo;
import com.hkts.naturalgas.utils.BeanConvertUtils;
import com.hkts.naturalgas.utils.Result;
import com.hkts.naturalgas.utils.ResultUtil;
import com.hkts.naturalgas.utils.SnowFlakeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 流程实例表 服务实现类
 * </p>
 *
 * @author zy
 * @since 2022-08-31
 */
@Service
@Transactional
public class FlowInstanceinfoServiceImpl extends ServiceImpl<FlowInstanceinfoMapper, FlowInstanceinfo> implements IFlowInstanceinfoService {


    @Autowired
    private FlowInstanceinfoMapper flowInstanceinfoMapper;

    @Autowired
    private FlowTemplateinfoMapper flowTemplateinfoMapper;
    @Autowired
    private IFlowTaskInstanceService iFlowTaskInstanceService;
    @Autowired
    private IFlowUserinfoService iFlowUserinfoService;

    @Autowired
    private HontUserMapper hontUserMapper;
    @Autowired
    private FeignInterface feignInterface;
    @Autowired
    private IFlowTemplateinfoCopyService iFlowTemplateinfoCopyService;


    @Override
    public IPage<FlowInstanceinfo> selectPage(Page<FlowInstanceinfo> page, FlowInstanceinfo flowInstanceinfo) {
        QueryWrapper<FlowInstanceinfo> query = Wrappers.query();
        QueryWrapper<FlowInstanceinfo> entityWrapper = getEntityWrapper(query, flowInstanceinfo);
        return flowInstanceinfoMapper.selectPage(page, entityWrapper);
    }


    @Override
    public List<FlowInstanceinfo> selectList(FlowInstanceinfo flowInstanceinfo) {
        QueryWrapper<FlowInstanceinfo> query = Wrappers.query();
        QueryWrapper<FlowInstanceinfo> entityWrapper = getEntityWrapper(query, flowInstanceinfo);
        return flowInstanceinfoMapper.selectList(entityWrapper);
    }

    /**
     * 公共查询条件
     *
     * @param entityWrapper
     * @return
     */
    public QueryWrapper<FlowInstanceinfo> getEntityWrapper(QueryWrapper<FlowInstanceinfo> entityWrapper, FlowInstanceinfo flowInstanceinfo) {


        return entityWrapper;
    }

    @Override
    public Result<Object> initiateProcess(FlowInstanceinfo flowInstanceinfo) {
        HontUserTo u = feignInterface.remoteUserInfo();
        boolean flag=iFlowUserinfoService.checkAuth(flowInstanceinfo.getTemplateId(),flowInstanceinfo.getTemplateVersion(),u);
        if(!flag){
            return ResultUtil.error("您没有权限发起此流程");
        }
        FlowTemplateinfo flowTemplateinfo=
                flowTemplateinfoMapper.selectById(flowInstanceinfo.getTemplateId());
        String id=String.valueOf(SnowFlakeUtil.getFlowIdInstance().nextId());
        flowInstanceinfo.setId(id);
        flowInstanceinfo.setFlowCreateTime(LocalDateTime.now());
//        flowInstanceinfo.setTemplateId(flowTemplateinfo.getId());
        flowInstanceinfo.setFlowName(flowTemplateinfo.getTemplateName());
        flowInstanceinfo.setFlowStatus(FlowInstanceinfo.FLOW_STATUS_RUNNING);
        flowInstanceinfo.setTemplateVersion(flowTemplateinfo.getTemplateVersion());
        flowInstanceinfo.setIsOrganization(flowTemplateinfo.getIsOrganization());
        flowInstanceinfo.setFlowHandlerId(u.getId());
        flowInstanceinfo.setFlowHandler(u.getNickName());
        // 添加流程发起人数据
        HontUserRolelevelQueryVo hontUserRolelevelQueryVo=new HontUserRolelevelQueryVo();
        hontUserRolelevelQueryVo.setUserId(u.getId());
        List<HontUserRolelevelVo> hontUserRolelevelVos=
                hontUserMapper.getHontUserAndRoleAndLevel(hontUserRolelevelQueryVo);
        HontUserRolelevelVo hontUserRolelevelVo=hontUserRolelevelVos.get(0);
        //添加任务实例
        Result<Object> result=  iFlowTaskInstanceService.addFlowTaskInstance(flowInstanceinfo,
                flowTemplateinfo,hontUserRolelevelVo.getRoleLevel());
        if(!result.isSuccess()){
            return result;
        }
         //添加抄送人
        if(flowTemplateinfo.getIsEnableCopy()==1){
            iFlowTemplateinfoCopyService.addFlowTemplateinfoCopy(flowInstanceinfo);
        }
        //添加流程实例
        flowInstanceinfoMapper.insert(flowInstanceinfo);

        Result<Object> approval= iFlowTaskInstanceService.approval(id);
        Map data=BeanConvertUtils.objectToMap(result.getResult());
        if(approval.isSuccess()){

            data.put("finish", approval.getResult().toString());
        }else {
            data.put("finish", "false");

        }

        data.put("instanceinfo",id);
        return ResultUtil.data(data);
    }


    @Override
    public Result<Object> initiateProcessByOverTime(FlowInstanceinfo flowInstanceinfo,String assessmentStatus) {
        HontUserTo u = feignInterface.remoteUserInfo();
        boolean flag=iFlowUserinfoService.checkAuth(flowInstanceinfo.getTemplateId(),flowInstanceinfo.getTemplateVersion(),u);
        if(!flag){
            return ResultUtil.error("您没有权限发起此流程");
        }
        FlowTemplateinfo flowTemplateinfo=
                flowTemplateinfoMapper.selectById(flowInstanceinfo.getTemplateId());
        String id=String.valueOf(SnowFlakeUtil.getFlowIdInstance().nextId());
        flowInstanceinfo.setId(id);
        flowInstanceinfo.setFlowCreateTime(LocalDateTime.now());
//        flowInstanceinfo.setTemplateId(flowTemplateinfo.getId());
        flowInstanceinfo.setFlowName(flowTemplateinfo.getTemplateName());
        flowInstanceinfo.setFlowStatus(FlowInstanceinfo.FLOW_STATUS_RUNNING);
        flowInstanceinfo.setTemplateVersion(flowTemplateinfo.getTemplateVersion());
        flowInstanceinfo.setIsOrganization(flowTemplateinfo.getIsOrganization());
        flowInstanceinfo.setFlowHandlerId(u.getId());
        flowInstanceinfo.setFlowHandler(u.getNickName());
        // 添加流程发起人数据
        HontUserRolelevelQueryVo hontUserRolelevelQueryVo=new HontUserRolelevelQueryVo();
        hontUserRolelevelQueryVo.setUserId(u.getId());
        List<HontUserRolelevelVo> hontUserRolelevelVos=
                hontUserMapper.getHontUserAndRoleAndLevel(hontUserRolelevelQueryVo);
        HontUserRolelevelVo hontUserRolelevelVo=hontUserRolelevelVos.get(0);
        //添加任务实例
        Result<Object> result=  iFlowTaskInstanceService.addFlowTaskInstance(flowInstanceinfo,
                flowTemplateinfo,hontUserRolelevelVo.getRoleLevel());
        if(!result.isSuccess()){
            return result;
        }
        //添加抄送人
        if(flowTemplateinfo.getIsEnableCopy()==1){
            iFlowTemplateinfoCopyService.addFlowTemplateinfoCopy(flowInstanceinfo);
        }
        //添加流程实例
        flowInstanceinfoMapper.insert(flowInstanceinfo);

        Result<Object> approval= iFlowTaskInstanceService.approval(id,assessmentStatus);
        Map data=BeanConvertUtils.objectToMap(result.getResult());
        if(approval.isSuccess()){

            data.put("finish", approval.getResult().toString());
        }else {
            data.put("finish", "false");

        }

        data.put("instanceinfo",id);
        return ResultUtil.data(data);
    }

    @Override
    public Result<Object> cancelProcess(String id) {
        FlowInstanceinfo flowInstanceinfo=new FlowInstanceinfo();
        flowInstanceinfo.setId(id);
        flowInstanceinfo.setFlowStatus(FlowInstanceinfo.NODE_TYPE_CANCEL);
        flowInstanceinfoMapper.updateById(flowInstanceinfo);
        return ResultUtil.success("");
    }

    @Override
    public Result<Object> getBackLog() {
        HontUserTo u = feignInterface.remoteUserInfo();
        return ResultUtil.data( flowInstanceinfoMapper.getBackLog(u.getId(),"1"));
    }

    @Override
    public Result<Object> getCopy() {
        HontUserTo u = feignInterface.remoteUserInfo();
        return ResultUtil.data( flowInstanceinfoMapper.getCopy(u.getId()));
    }
}
